#pragma once
#include "comm.hpp"
#include <time.h>
#include <stdarg.h>
#include <cstring>
#define Info 1
#define Debug 2
#define Warning 3
#define Error 4
#define Fatal 5
#define SCREEN 1 //屏幕打印
#define ONEFILE 2  //打印某个文件
#define CLASSFILE 3  //分类打印
#define FILE_NAME "log.txt"
#define PATH "./log/"
class Log
{
    public:
    Log()
    {
        printmethod=SCREEN;//默认向屏幕打印
        path=PATH;
    }
   void Enable(int method)
   {
    printmethod=method;
   }
std::string leveltoString(int level)
{
    switch(level)
    {
        case 1:
        return "Info";
        case 2:
        return "Debug";
        case 3:
        return "Warning";
        case 4:
        return "Error";
        case 5:
        return "Fatal";
        default:
        return "None";
    }
}
void printOnefile(const std::string&filename,const std::string&logtxt)//向一个文件打印
{
    std::string Filename=path+filename;
    int fd=open(Filename.c_str(),O_CREAT|O_WRONLY|O_APPEND);
    write(fd,logtxt.c_str(),logtxt.size());
    close(fd);
}
void printClassfile(int level,const std::string&logtxt)
{
    std::string filename=FILE_NAME;
    filename+=".";
    filename+=leveltoString(level);
    printOnefile(filename,logtxt);
}
void logprint(int level,const std::string&logtxt)
{
    switch(printmethod)
    {
        case SCREEN:std::cout<<logtxt.c_str()<<std::endl;
        break;
        case ONEFILE:printOnefile(FILE_NAME,logtxt);
        break;
        case CLASSFILE:printClassfile(level,logtxt);
        break;
    }
}
void operator()(int level,const char*format,...)
{
    time_t t=time(nullptr);//获取时间戳
    struct tm*ctime=localtime(&t);//通过时间戳获取想要的时间

    //leftbuffer为默认信息包括：日志等级、日志时间
    char leftbuffer[SIZE]={0};
    snprintf(leftbuffer,sizeof(leftbuffer),"[%s][%d-%d-%d %d:%d:%d]",leveltoString(level).c_str(),
    ctime->tm_year+1900,ctime->tm_mon+1,ctime->tm_mday,
    ctime->tm_hour,ctime->tm_min,ctime->tm_sec);
    //rightbuffer 为自定义消息
    char rightbuffer[SIZE]={0};
    va_list s;//相当于char*
    va_start(s,format);//取format内容后s指针往上走，相当于走到可变参数的起始位置
    vsnprintf(rightbuffer,sizeof(rightbuffer),format,s);
    //左右buffer拼接
    char logtxt[SIZE*2]={0};
    snprintf(logtxt,sizeof(logtxt),"%s %s\n",leftbuffer,rightbuffer);
    logprint(level,logtxt);

}
private:
    int printmethod;
    std::string path;
};